// 好友请求服务
import { apiService } from './api'
import type { 
  FriendRequest,
  SendFriendRequestRequest,
  ProcessFriendRequestRequest,
  RejectFriendRequestRequest,
  FriendRequestPageResponse,
  PendingRequestCountResponse,
  CanSendRequestResponse
} from '@/types'

export class FriendRequestService {
  /**
   * 发送好友请求
   */
  async sendFriendRequest(request: SendFriendRequestRequest): Promise<FriendRequest> {
    const response = await apiService.userPost<FriendRequest>('/api/friend-requests', request)
    if (!response.success || !response.data) {
      throw new Error(response.message || '发送好友请求失败')
    }
    return response.data
  }

  /**
   * 接受好友请求
   */
  async acceptFriendRequest(requestId: number, userId: number): Promise<void> {
    const request: ProcessFriendRequestRequest = { userId }
    const response = await apiService.userPost<void>(`/api/friend-requests/${requestId}/accept`, request)
    if (!response.success) {
      throw new Error(response.message || '接受好友请求失败')
    }
  }

  /**
   * 拒绝好友请求
   */
  async rejectFriendRequest(requestId: number, userId: number, reason?: string): Promise<void> {
    const request: RejectFriendRequestRequest = { userId, reason }
    const response = await apiService.userPost<void>(`/api/friend-requests/${requestId}/reject`, request)
    if (!response.success) {
      throw new Error(response.message || '拒绝好友请求失败')
    }
  }

  /**
   * 取消好友请求
   */
  async cancelFriendRequest(requestId: number, userId: number): Promise<void> {
    const request: ProcessFriendRequestRequest = { userId }
    const response = await apiService.userPost<void>(`/api/friend-requests/${requestId}/cancel`, request)
    if (!response.success) {
      throw new Error(response.message || '取消好友请求失败')
    }
  }

  /**
   * 获取收到的好友请求
   */
  async getReceivedRequests(userId: number, page = 0, size = 20): Promise<FriendRequestPageResponse> {
    const response = await apiService.userGet<FriendRequestPageResponse>(
      `/api/friend-requests/received?userId=${userId}&page=${page}&size=${size}`
    )
    if (!response.success || !response.data) {
      throw new Error(response.message || '获取收到的好友请求失败')
    }
    return response.data
  }

  /**
   * 获取发送的好友请求
   */
  async getSentRequests(userId: number, page = 0, size = 20): Promise<FriendRequestPageResponse> {
    const response = await apiService.userGet<FriendRequestPageResponse>(
      `/api/friend-requests/sent?userId=${userId}&page=${page}&size=${size}`
    )
    if (!response.success || !response.data) {
      throw new Error(response.message || '获取发送的好友请求失败')
    }
    return response.data
  }

  /**
   * 获取待处理请求数量
   */
  async getPendingRequestCount(userId: number): Promise<number> {
    const response = await apiService.userGet<PendingRequestCountResponse>(
      `/api/friend-requests/pending-count?userId=${userId}`
    )
    if (!response.success || !response.data) {
      throw new Error(response.message || '获取待处理请求数量失败')
    }
    return response.data.count
  }

  /**
   * 检查是否可以发送好友请求
   */
  async canSendFriendRequest(fromUserId: number, toUserId: number): Promise<boolean> {
    const response = await apiService.userGet<CanSendRequestResponse>(
      `/api/friend-requests/can-send?fromUserId=${fromUserId}&toUserId=${toUserId}`
    )
    if (!response.success || !response.data) {
      throw new Error(response.message || '检查发送权限失败')
    }
    return response.data.canSend
  }

  /**
   * 获取所有收到的请求（不分页）
   */
  async getAllReceivedRequests(userId: number): Promise<FriendRequest[]> {
    const allRequests: FriendRequest[] = []
    let page = 0
    let hasMore = true
    
    while (hasMore) {
      try {
        const result = await this.getReceivedRequests(userId, page, 50)
        allRequests.push(...result.content)
        hasMore = page < result.totalPages - 1
        page++
      } catch (error) {
        console.error('Error fetching received requests:', error)
        break
      }
    }
    
    return allRequests
  }

  /**
   * 获取所有发送的请求（不分页）
   */
  async getAllSentRequests(userId: number): Promise<FriendRequest[]> {
    const allRequests: FriendRequest[] = []
    let page = 0
    let hasMore = true
    
    while (hasMore) {
      try {
        const result = await this.getSentRequests(userId, page, 50)
        allRequests.push(...result.content)
        hasMore = page < result.totalPages - 1
        page++
      } catch (error) {
        console.error('Error fetching sent requests:', error)
        break
      }
    }
    
    return allRequests
  }

  /**
   * 批量处理好友请求
   */
  async batchProcessRequests(
    requests: { requestId: number; action: 'accept' | 'reject'; reason?: string }[],
    userId: number
  ): Promise<{ success: number; failed: number; errors: string[] }> {
    const results = {
      success: 0,
      failed: 0,
      errors: [] as string[]
    }

    const promises = requests.map(async (req) => {
      try {
        if (req.action === 'accept') {
          await this.acceptFriendRequest(req.requestId, userId)
        } else {
          await this.rejectFriendRequest(req.requestId, userId, req.reason)
        }
        results.success++
      } catch (error) {
        results.failed++
        results.errors.push(`请求${req.requestId}: ${error instanceof Error ? error.message : '未知错误'}`)
      }
    })

    await Promise.allSettled(promises)
    return results
  }
}

export const friendRequestService = new FriendRequestService()